/*------------------------------------------------------------------------------
 * PROJ : Prototype
 * NAME : sculove.spring.framework.advisor.RequestTokenCheckAdvice.java
 *        
 * Copyright 2009 sculove All rights reserved
 *------------------------------------------------------------------------------
*/
package sculove.spring.framework.advice;

import javax.servlet.http.HttpServletRequest;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sculove.spring.framework.util.Configuration;
import sculove.spring.framework.util.RequestToken;

/**
 * <pre>
 * sculove.spring.framework.advisor.RequestTokenCheckAdvice.java
 * TODO
 * 
 * </pre>
 * @date : 2009. 12. 11. 오전 10:16:26
 * @version :
 * @author : sculove
 */
public class RequestTokenCheckAdvice implements MethodInterceptor {
	private Log logger = LogFactory.getLog(this.getClass()); 
	
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		if (logger.isDebugEnabled()) logger.debug("★★★ ReqeustTokenAdvisor [" + invocation.getMethod().getName() + "] ★★★");
		/*
		 * Arguments Analysis
		 */
		Object[] args = invocation.getArguments();
		HttpServletRequest request = null;
		
		for(Object obj : args) {
			if(obj instanceof HttpServletRequest) {
				request = (HttpServletRequest)obj;
			}
		}

		/*
		 * check Request-Token
		 */
		try {
			if(!RequestToken.isValid(request)) {
				if(logger.isDebugEnabled()) logger.debug("★★★ ReqeustTokenAdvisor [" + invocation.getMethod().getName() + "] Fail ★★★");
				return Configuration.getPropInstance().getString("com.requestToken.forward-page");
			} else {
				return invocation.proceed();
			}
		} catch (Exception e) {
			if(logger.isDebugEnabled()) logger.debug("★★★ HttpServletRequest 또는 HttpServletResponse가 Method Arguments에 존재하지 않습니다. ★★★");
			throw e;
		}
	}
}
